package com.qeado.content.web;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.qeado.common.UploadFileLocation;
import com.qeado.common.helper.AttributeHelper;
import com.qeado.content.model.AdManage;
import com.qeado.content.model.AdTypeCode;
import com.qeado.content.service.AdManageService;



@Controller
public class AdManageController {
	
	@Autowired
	private AdManageService adManageService;
	
	@RequestMapping("/adManage.ac")
	public String showAdManageMainMenu(HttpServletRequest request){
		AttributeHelper.removeSessionAttribute(request, "T_");
		List<AdTypeCode> adTypeList = this.adManageService.getAllAdTypeList();
		List<AdTypeCode> adLocationList = this.adManageService.getAllAdLocationList();
		request.getSession().setAttribute("T_adTypeList", adTypeList);
		request.getSession().setAttribute("T_adLocationList", adLocationList);
		return "content/ad_search";
	}
	
	@RequestMapping("/searchAd.ac")
	public ModelAndView searchAdByTypeAndDesc(AdManage ad){	
		List<AdManage> adList = this.adManageService.getAdByTypeAndDesc(ad);
		return new ModelAndView("content/ad_search","adList",adList);
	}
	
	@RequestMapping("/deleteAd.ac")
	public ModelAndView deleteAdById(String id){
		adManageService.deleteAdManageById(id);
		List<AdManage> adList = this.adManageService.getAdByTypeAndDesc(null);
		return new ModelAndView("content/ad_search","adList",adList);
	}
	
	@RequestMapping("/selectAd.ac")
	public ModelAndView selectAdById(String id){
		AdManage adManage = adManageService.selectAdManageById(id);
		return new ModelAndView("content/ad_new", "adManage", adManage);
	}
	
	@RequestMapping("/adBack.ac")
	public String adBack(){	
		return "content/ad_search";
	} 
	
	@RequestMapping("/detailAd.ac")
	public String createNewAd(){	
		return "content/ad_new";
	} 
	
	@RequestMapping("/getAdContent.ac")
	public void getAdContent(HttpServletResponse response, String fileName) throws UnsupportedEncodingException{	
		fileName = URLEncoder.encode(fileName,"UTF-8");
	    response.addHeader("Content-Disposition","attachment;filename=" + fileName);
	    OutputStream output = null;
	    FileInputStream fis = null;
	    try {
	        output = response.getOutputStream();
	        File file = new File(UploadFileLocation.BASE_DIR + "\\ad\\" +fileName);
	        fis = new FileInputStream(file);
	        byte[] b = new byte[1024];
	        int i = 0;
	        while((i = fis.read(b)) > 0) {
	            output.write(b, 0, i);
	        }
	        output.flush();
	    } catch(Exception e) {
	        e.printStackTrace();
	    } finally {
	        if(fis != null) { 
	        	try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
	        }
	        if(output != null) {
	        	try {
					output.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
	        }
	    }
	} 
	
	@RequestMapping("/saveNewAd.ac")
	public String savaOrModifiedAd(HttpServletRequest request, AdManage ad) throws IOException{	
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
		MultipartFile file = multipartRequest.getFile("localFile");
		if(!file.isEmpty()) {
			String imgName = getFileNameByTime(file.getOriginalFilename());
			try {
				String path = UploadFileLocation.BASE_DIR + "\\ad" ;
				if(!"".equals(ad.getAdFilename())) {
					File oldFile = new File(path + "\\" + ad.getAdFilename());
					oldFile.delete();
				}
				File uploadedFile = new File(path + "\\" + imgName);
				int v;         
				BufferedInputStream inputStream = new BufferedInputStream(file.getInputStream());     
				FileOutputStream outputStream = new FileOutputStream(uploadedFile);     
				byte [] bytes = new byte[1024];     
				while((v = inputStream.read(bytes)) > 0){     
				    outputStream.write(bytes, 0, v);     
				}     
				outputStream.close();     
				inputStream.close();	
			} catch (Exception e) {
				e.printStackTrace();
			}
			ad.setAdFilename(imgName);
		}
		//ad.setAdContent(file.getBytes());
		this.adManageService.saveNewAd(ad);
		return "content/ad_new";
	} 
	
	private synchronized String getFileNameByTime(String input){
        int index = input.lastIndexOf(".");
        return System.currentTimeMillis() + input.substring(index);
    }
	
}
